package org.ranki.moerae.atropos;


import org.ranki.moerae.clotho.node.AbstractNode;

import java.util.HashSet;
import java.util.Set;

public class EliminateLoopback implements Eliminate{
    private volatile static EliminateLoopback eliminateLoopback;
    private EliminateLoopback (){}
    public static EliminateLoopback getEliminateLoopback() {
        if (eliminateLoopback == null) {
            synchronized (EliminateLoopback.class) {
                if (eliminateLoopback == null) {
                    eliminateLoopback = new EliminateLoopback();
                }
            }
        }
        return eliminateLoopback;
    }

    @Override
    public void eliminate(AbstractNode abstractNode) {
        dfs(abstractNode,new HashSet<AbstractNode>());
    }
    private void dfs(AbstractNode curr, Set<AbstractNode> seen){
        seen.add(curr);
        for(AbstractNode next: curr.getNexts()){
            if(seen.contains(next)){
                curr.getNexts().remove(next);
                continue;
            }
            dfs(next,seen);
        }
        seen.remove(curr);
    }
}
